package com.wzh.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import com.wzh.common.utils.JwtUtil;
import com.wzh.common.utils.R;
import com.wzh.user.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.user.dao.HouseUserDao;
import com.wzh.user.entity.HouseUserEntity;
import com.wzh.user.service.HouseUserService;


@Service("houseUserService")
public class HouseUserServiceImpl extends ServiceImpl<HouseUserDao, HouseUserEntity> implements HouseUserService {

    @Autowired
    private HouseUserDao houseUserDao;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${register.salt}")
    private String salt;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<HouseUserEntity> w = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)){
            w.like("username",key);
        }
        IPage<HouseUserEntity> page = this.page(
                new Query<HouseUserEntity>().getPage(params),
                w
        );

        return new PageUtils(page);
    }

    @Override
    public R login(String username,String password) {
        HouseUserEntity userEntity=houseUserDao.login(username);
        if (userEntity!=null){
            if (userEntity.getPassword().equals(Md5Util.md5salt(Md5Util.md5salt(password,salt),salt))){
                String token = jwtUtil.createJWT(userEntity.getUserId().toString(), userEntity.getUsername(), "user");
                redisTemplate.opsForValue().set("user"+userEntity.getUserId(), JSON.toJSONString(userEntity),30, TimeUnit.MINUTES);
                return R.ok("登陆成功").put("token",token);
            }
            return R.error("用户名或密码错误");
        }
        return R.error("用户名或密码错误");
    }

    @Override
    public Integer checkUserName(String username) {
        Integer integer = baseMapper.selectCount(new QueryWrapper<HouseUserEntity>().eq("username", username));
        return integer;
    }

}